<template>
  <div class="channel-edit">
    <!-- 当前登陆用户已经订阅的频道 -->
    <div class="channel">

      <van-cell title="我的频道" :border="false">
        <van-button
          plain
          size="mini"
          type="danger"
          @click="isEditing = !isEditing"
        >
          {{ isEditing ? "取消" :"编辑" }}
        </van-button>
      </van-cell>

      <van-grid>
        <van-grid-item
          v-for="(item,index) in channels"
          :key="item.id"
          :class="{current: index === active}"
          @click="clickMychannel(index)"
        >
          <span>{{ item.name }}</span>
          <van-icon
            v-if="isEditing && index !== 0"
            name="cross"
            class="btn"
            @click="clickDelChannel(index)"
          />
        </van-grid-item>
      </van-grid>
    </div>

    <!-- 当前登陆用户没有订阅的频道 -->
    <div class="channel">
      <van-cell title="可选频道" :border="false" />
      <van-grid>
        <van-grid-item
          v-for="item in optionChannels"
          :key="item.id"
          @click="clickAddChannel(item)"
        >
          <span>{{ item.name }}</span>
        </van-grid-item>
      </van-grid>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations, mapActions, mapGetters } from 'vuex'
import { reqSetChannels } from '@/api/channels'

export default {
  name: 'ChannelEdit',

  props: {
    active: {
      type: Number,
      default: 0
    }
  },

  data() {
    return {
      isEditing: false
    }
  },

  computed: {
    ...mapState('channels', ['channels']),
    ...mapGetters('channels', ['optionChannels'])
  },

  created() {
    this.getAllChannelsAsync()
  },

  methods: {
    ...mapActions('channels', ['getAllChannelsAsync']),
    ...mapMutations('channels', ['addChannels']),
    ...mapMutations('channels', ['delChannels']),

    // 切换频道
    clickMychannel(index) {
      if (this.isEditing === true) return
      this.$emit('update-current', index)
    },

    // 添加频道
    clickAddChannel(channel) {
      // 前端操作数据，修改我的频道
      this.addChannels(channel)
      // 将数据同步到后台
      this.resetChannel()
    },

    // 删除频道
    clickDelChannel(index) {
      if (index === this.active) this.$emit('update-active', 0)
      if (index < this.active) this.$emit('update-active', this.active - 1)
      // 前端操作数据，修改我的频道
      this.delChannels(index)
      // 将数据同步到后台
      this.resetChannel()
    },

    // 封装同步数据方法
    async resetChannel() {
      const channelList = this.channels.map((item, index) => {
        return {
          id: item.id,
          seq: index
        }
      })
      await reqSetChannels(channelList)
    }
  }

}
</script>

<style lang="scss" scoped>
.channel{
  padding:15px;
  font-size:14px;

  ::v-deep .van-button--mini {
    height: 22px;
    min-width: 50px;
  }

  .btn {
    position: absolute;
    top: 5px;
    right: 5px;
    font-size: 14px;
  }

  .current {
  color: #e5615b;
  font-weight: bold;
}
}
</style>
